package com.estar.assistsurvy.utils;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;

import android.graphics.Bitmap;
import android.graphics.Bitmap.CompressFormat;
import android.graphics.Bitmap.Config;
import android.os.Environment;
import android.graphics.Canvas;
import android.util.Log;
import android.view.View;

public class BMapUtil {
	/*
	 * 工具类
	 */

	public static final String PATH=Environment.getExternalStorageDirectory()+File.separator+"Bitmaps/";

	//从view得到bitmap：
	public static Bitmap getBitmapFromView(View view) {  
		Bitmap bitmap = null;  
		try {  
			int width = view.getWidth();  
			int height = view.getHeight();  
			if(width != 0 && height != 0){  
				bitmap = Bitmap.createBitmap(width, height, Bitmap.Config.ARGB_8888);  
				Canvas canvas = new Canvas(bitmap);  
				view.layout(0, 0, width, height);  
				view.draw(canvas);  
			}  
		} catch (Exception e) {  
			bitmap = null;  
			e.getStackTrace();  
		}  
		return bitmap;  
	} 

	//Bitmap加水印：
	public static Bitmap addWatermark(Bitmap src, Bitmap watermark) {  
		if (src == null || watermark  == null) {  
			Log.d("wl", "src is null");  
			return src;  
		}  

		int sWid = src.getWidth();  
		int sHei = src.getHeight();  
		int wWid = watermark.getWidth();  
		int wHei = watermark.getHeight();  
		if (sWid == 0 || sHei == 0) {  
			return null;  
		}  

		if (sWid < wWid || sHei < wHei) {  
			return src;  
		}  

		Bitmap bitmap = Bitmap.createBitmap(sWid, sHei, Config.ARGB_8888);  
		try {  
			Canvas cv = new Canvas(bitmap);  
			cv.drawBitmap(src, 0, 0, null);  
			cv.drawBitmap(watermark, sWid - wWid - 5, sHei - wHei - 5, null);  
			cv.save(Canvas.ALL_SAVE_FLAG);  
			cv.restore();  
		} catch (Exception e) {  
			bitmap = null;  
			e.getStackTrace();  
		}  
		return bitmap;  
	}  

	//Bitmap保存：
	public static boolean saveBitmap(Bitmap bitmap, String fileName) {  
		File file = new File(PATH);  
		if (!file.exists()) {  
			file.mkdir();  
		}  
		File imageFile = new File(file, fileName);  
		try {  
			imageFile.createNewFile();  
			FileOutputStream fos = new FileOutputStream(imageFile);  
			bitmap.compress(CompressFormat.JPEG, 50, fos);  
			fos.flush();  
			fos.close();  
		} catch (FileNotFoundException e) {  
			e.printStackTrace();  
		} catch (IOException e) {  
			e.printStackTrace();  
		}  
		return true;  
	}  
}
